import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { X, Save } from "lucide-react";

export default function OperationalUnitForm({ unit, onSubmit, onCancel }) {
  const [localUnit, setLocalUnit] = useState({
    name: "",
    type: "constructionUnit",
    resource_capacity: {
      max_concurrent_teams: "",
      max_projects: ""
    },
    contact_person: "",
    contact_phone: "",
    ...unit
  });

  useEffect(() => {
    if (unit) {
      setLocalUnit({
        ...unit,
        resource_capacity: {
          max_concurrent_teams: unit.resource_capacity?.max_concurrent_teams || "",
          max_projects: unit.resource_capacity?.max_projects || ""
        }
      });
    }
  }, [unit]);

  const handleFieldChange = (field, value) => {
    setLocalUnit(prev => ({ ...prev, [field]: value }));
  };

  const handleResourceCapacityChange = (field, value) => {
    setLocalUnit(prev => ({
      ...prev,
      resource_capacity: {
        ...prev.resource_capacity,
        [field]: value
      }
    }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    
    // Clean up empty resource capacity fields
    const cleanedUnit = {
      ...localUnit,
      resource_capacity: {
        max_concurrent_teams: localUnit.resource_capacity.max_concurrent_teams 
          ? parseInt(localUnit.resource_capacity.max_concurrent_teams) 
          : undefined,
        max_projects: localUnit.resource_capacity.max_projects 
          ? parseInt(localUnit.resource_capacity.max_projects) 
          : undefined
      }
    };

    // Remove undefined values
    Object.keys(cleanedUnit.resource_capacity).forEach(key => {
      if (cleanedUnit.resource_capacity[key] === undefined) {
        delete cleanedUnit.resource_capacity[key];
      }
    });

    onSubmit(cleanedUnit);
  };

  const unitTypes = [
    { value: "constructionUnit", label: "施工单位" },
    { value: "designUnit", label: "设计单位" },
    { value: "supervisionUnit", label: "监理单位" }
  ];

  return (
    <Card className="mb-6 shadow-lg border-green-200">
      <CardHeader className="bg-green-50">
        <CardTitle className="flex items-center justify-between">
          <span>{unit ? '编辑作业单位' : '新建作业单位'}</span>
          <Button variant="ghost" size="icon" onClick={onCancel}>
            <X className="w-4 h-4" />
          </Button>
        </CardTitle>
      </CardHeader>

      <CardContent className="p-6">
        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="name">单位名称 *</Label>
              <Input
                id="name"
                value={localUnit.name}
                onChange={(e) => handleFieldChange("name", e.target.value)}
                placeholder="如：第一施工单位"
                required
              />
            </div>

            <div>
              <Label htmlFor="type">单位类型 *</Label>
              <Select
                value={localUnit.type}
                onValueChange={(value) => handleFieldChange("type", value)}
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择单位类型" />
                </SelectTrigger>
                <SelectContent>
                  {unitTypes.map(type => (
                    <SelectItem key={type.value} value={type.value}>
                      {type.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor="contact_person">联系人</Label>
              <Input
                id="contact_person"
                value={localUnit.contact_person}
                onChange={(e) => handleFieldChange("contact_person", e.target.value)}
                placeholder="负责人姓名"
              />
            </div>

            <div>
              <Label htmlFor="contact_phone">联系电话</Label>
              <Input
                id="contact_phone"
                value={localUnit.contact_phone}
                onChange={(e) => handleFieldChange("contact_phone", e.target.value)}
                placeholder="联系电话"
              />
            </div>
          </div>

          {/* Resource Capacity */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-gray-900">资源承载能力</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label htmlFor="max_concurrent_teams">最大并行施工队数</Label>
                <Input
                  id="max_concurrent_teams"
                  type="number"
                  min="1"
                  value={localUnit.resource_capacity.max_concurrent_teams}
                  onChange={(e) => handleResourceCapacityChange("max_concurrent_teams", e.target.value)}
                  placeholder="如：3"
                />
                <p className="text-xs text-gray-500 mt-1">同时可投入施工的队伍数量</p>
              </div>

              <div>
                <Label htmlFor="max_projects">最大管理项目数</Label>
                <Input
                  id="max_projects"
                  type="number"
                  min="1"
                  value={localUnit.resource_capacity.max_projects}
                  onChange={(e) => handleResourceCapacityChange("max_projects", e.target.value)}
                  placeholder="如：5"
                />
                <p className="text-xs text-gray-500 mt-1">同时可管理的项目总数</p>
              </div>
            </div>
          </div>

          <div className="flex justify-end gap-3 pt-4 border-t">
            <Button type="button" variant="outline" onClick={onCancel}>
              <X className="w-4 h-4 mr-2" />
              取消
            </Button>
            <Button type="submit" className="bg-green-600 hover:bg-green-700">
              <Save className="w-4 h-4 mr-2" />
              保存单位
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}